//
//  CJPicSelectViewController.swift
//  SinaWeibo
//
//  Created by 程建 on 16/10/7.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

let selectCellMargin:CGFloat = 4
let colCount = 3
let itemW = (ScreenWidth - (CGFloat(colCount) + 1)*selectCellMargin) / CGFloat(colCount)

private let maxImageCount = 5

class CJPicSelectViewController: UICollectionViewController {

    //懒加载图片类型数组
    lazy var images:[UIImage] = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.register(CJPicSelectCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        
        let imageCount = images.count
        
        //限制图片最大添加张数
        let count = imageCount + (imageCount == maxImageCount ? 0:1)
        return count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CJPicSelectCell
    
        cell.backgroundColor = UIColor.yellow
        
        cell.delegate = self
        
        if indexPath.item == images.count {
            //需要给额外添加cell进行赋值图片的操作
            cell.image = nil
        }else {
            //不是额外添加的cell
            cell.image = images[indexPath.item]
        }
        
       
    
        return cell
    }
}

//在分类中遵守协议,实现代理方法
extension CJPicSelectViewController: CJPicSelectCellDelegate {
    
    func userWillAddPic() {
        //调用图片选择器  添加图片
        let picker = UIImagePickerController()
        
        //使用代理方法获取图片
        picker.delegate = self
        
        present(picker, animated: true, completion: nil)
        
    }
    
    func userWillRemovePic(cell:CJPicSelectCell) {
        
        //1.在数组中删除 '对应' 的元素
        let indexPath = collectionView?.indexPath(for: cell)
        self.images.remove(at: indexPath!.item)
        self.view.isHidden = images.count == 0
        
        //2.刷新数据
        self.collectionView?.reloadData()
    }
    
}

//在分类中实现代理方法
extension CJPicSelectViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    //实现协议方法 没有实现协议方法之前 控制器可以自动dismiss
    //一旦实现了协议方法,控制器的dismiss就交给了程序员
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
       // print(info)
        //获取图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        //获取图片之后需要显示到contentView中
        //将图片添加到数组中
        images.append(image.scaleImage(width: 600))
        //刷新数据
        self.collectionView?.reloadData()
        dismiss(animated: true, completion: nil)
        
    }
    
}


@objc protocol CJPicSelectCellDelegate:NSObjectProtocol {
    
    //声明协议方法
    //用户将要添加图片
    @objc optional func userWillAddPic()
    
    //用户将要删除图片
    @objc optional func userWillRemovePic(cell:CJPicSelectCell)
}



//自定义cell 
class CJPicSelectCell:UICollectionViewCell {
    
    //声明代理属性 (弱引用)
    weak var delegate:CJPicSelectCellDelegate?
    
    //image
    var image: UIImage? {
        
        didSet{
            //设置addBtn的图片
            addBtn.setImage(image, for: .normal)
            //设置删除按钮的隐藏和显示
            removeBtn.isHidden = image == nil
            let backImage:UIImage? = image == nil ?#imageLiteral(resourceName: "compose_pic_add"):nil
            addBtn.setBackgroundImage(backImage, for: .normal)
            
        }
        
    }
    
    
    override init(frame: CGRect) {
        super.init(frame:frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        //添加按钮和删除按钮
        contentView.addSubview(addBtn)
        contentView.addSubview(removeBtn)
        
        //设置约束
        addBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        removeBtn.snp.makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
        
        addBtn.addTarget(self, action: #selector(addBtnDidClick), for: .touchUpInside)
        
        removeBtn.addTarget(self, action: #selector(removeBtnDidClick), for: .touchUpInside)
    }
    
    //按钮的点击方法
    @objc private func addBtnDidClick() {
        //通过代理对象实现代理方法
        //如果当前的cell的image不为nil 就表示就有图片了 
        if image != nil {
            print("人家已经有图片了")
            return
        }
        delegate?.userWillAddPic?()
    }
    
    @objc private func removeBtnDidClick() {
        //通过代理对象实现代理方法
        delegate?.userWillRemovePic?(cell:self)
    }
    
    
    //懒加载添加按钮
    private lazy var addBtn:UIButton = {
       
        let btn = UIButton()
        
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        
        
        return btn
    }()
    
    //懒加载删除按钮
    private lazy var removeBtn:UIButton = {
        
        let btn = UIButton()
       
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        
        return btn
    }()
    
    
}

